import { useCallback, useMemo, useState } from "react";
import { IPhotoData } from "../type";
import { defaultGlobalConfig } from "../config";
import { storageGetItem } from "../utils/storage";
import { ICanvasRef } from "../components/Canvas";
interface IProps {
  canvasRef: React.RefObject<ICanvasRef>;
}

const useIndex = (props: IProps) => {
  const { canvasRef } = props;

  const [photoList, setPhotoList] = useState<IPhotoData[]>([]);
  const [showPhotoIndex, setShowPhotoIndex] = useState(0);
  const [globalConfig, setGlobalConfig] = useState({
    ...defaultGlobalConfig,
    ...(storageGetItem("globalConfig") || {}),
  });

  const showPhoto = useMemo(
    () => photoList[showPhotoIndex],
    [photoList, showPhotoIndex]
  );

  const reRenderCanvas = useCallback(
    async (photoInfo: IPhotoData) => {
      const newData = await canvasRef.current?.renderPhotoContainer(
        photoInfo,
        true,
        true
      );
      setPhotoList((oldList) =>
        oldList.map((item) => (item.id === newData!.id ? newData! : item))
      );
    },
    [canvasRef]
  );

  return {
    context: {
      globalConfig,
      showPhoto,
      photoList,
      setPhotoList,
      showPhotoIndex,
      setShowPhotoIndex,
      setGlobalConfig,
      reRenderCanvas,
    },
  };
};

export default useIndex;
